package cn.kailangtu.myapplication.services;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;

import cn.kailangtu.myapplication.data.CanDataManager;
import cn.kailangtu.myapplication.events.CanDataSendEvent;
import cn.kailangtu.myapplication.events.SerialData;
import cn.kailangtu.myapplication.events.SerialDataRS481;
import cn.kailangtu.myapplication.tools.APPSPUtils;
import cn.kailangtu.serialport.CommonUtils;
import cn.kailangtu.serialport.ReceiveData;
import cn.kailangtu.serialport.ReceiveMsgListener;
import cn.kailangtu.serialport.SerialPortApi;
import cn.kailangtu.serialportv2.DataVersion2;

public class SerialDataService extends Service {

    private LinkedBlockingQueue<ReceiveData> receiveMsgQueue = new LinkedBlockingQueue<>();
    // private LinkedBlockingQueue<ReceiveData> receiveMsgQueuers4851 = new LinkedBlockingQueue<>();

    SerialPortApi serialPortApi = new SerialPortApi();

    public SerialDataService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        init();

    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onMessageEvent(CanDataSendEvent event) {
        // binding.textviewFirst.setText(event.toString());
        //  Log.e("wwwwww","uuuu");
        serialPortApi.send(event.getFrameId(), event.getData(), event.isStandard());
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }


    @SuppressLint("ForegroundServiceType")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


        //启动服务用
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("persident", "persident",
                    NotificationManager.IMPORTANCE_LOW);
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.createNotificationChannel(channel);
            Notification notification = new NotificationCompat.Builder(this, "persident")
                    .setAutoCancel(true)
                    .setCategory(Notification.CATEGORY_SERVICE)
                    .setOngoing(true)
                    .setPriority(NotificationManager.IMPORTANCE_LOW).build();
            startForeground(12, notification);
        }

        return super.onStartCommand(intent, flags, startId);
    }

    private void init() {


        serialPortApi.openSerialPort("/dev/ttyHSL0", 115200, 0, new ReceiveMsgListener() {
            @Override
            public void errorMsg(String s) {
                Log.e("SerialDataService", "打开串口失败！！");
            }

            @Override
            public void portReceiveData(ReceiveData receiveData) {
                Log.d("kkkkkkk", "portReceiveData:" + receiveData.toString());

                //获取队列数据
                receiveMsgQueue.offer(receiveData);
            }

            @Override
            public void portReceiveDataEx(byte[] data) {

            }


        });
//
        ProcessThread thread = new ProcessThread();
        thread.start();
    }

    byte[] data_EventBus = new byte[60];

    private class ProcessThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (!isInterrupted()) {
                try {
                    ReceiveData receiveData = receiveMsgQueue.take();
                    byte[] data1 = receiveData.getData();
                    byte[] id = receiveData.getFrameId();
                    int frame = CommonUtils.byteArrayToInt(id);
                    CanDataManager.getInstance().setNewValue(frame, data1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    int 读取 = 0;
    float 行驶里程[];
    int id2ee_21 = 0;


    //合并成int
    public static int combineBytesToInt(byte byte1, byte byte2) {
        // 将byte1左移8位，空出的低位由byte2填充
        return (byte1 << 8) | (byte2 & 0xFF);
    }
}